package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constants.RedisConstant;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserInfoService userInfoService;


    @Override
    public void sendCode(String phone) {

        //缓存key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        //判断key是否存在
        Boolean hasKey = redisTemplate.hasKey(key);
        //存在
        if(hasKey){
            //获取验证码剩余有效时间
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            //获取验证码总有效时间
            Integer appLoginCodeTtlSec = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            //获取可发送的间隔时间
            Integer appLoginCodeResendTimeSec = RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC;
            //判断是否已超过发送间隔
            if(appLoginCodeTtlSec - expire < appLoginCodeResendTimeSec){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN );
            }
        }

        //生成随机的6位数字验证码
        String code = (int)((Math.random() + 1) * 100000) + "";
        System.out.println("验证码 = " + code);
        //保存验证码到redis中
        redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }


    @Override
    public String login(LoginVo loginVo) {

        //接收验证码
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        //获取redis中的验证码
        String redisCode = (String) redisTemplate.opsForValue().get(key);
        //对比->验证码不存在,验证码已过期,验证码错误
        if(redisCode == null ||!redisCode.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        //验证码正确
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取用户信息
        lambdaQueryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        //查询
        UserInfo userInfo = userInfoService.getOne(lambdaQueryWrapper);
        if(userInfo == null){
            userInfo = new UserInfo();
            //设置默认值
            userInfo.setPhone(loginVo.getPhone());
            //设置默认头像
            userInfo.setAvatarUrl("http://www.baidu.com/img/bd_logo.png");
            //设置默认昵称+手机号后四位
            userInfo.setNickname("佚名昵称" + loginVo.getPhone().substring(7));
            //默认正常状态
            userInfo.setStatus(BaseStatus.ENABLE);
            //保存
            userInfoService.save(userInfo);
        }

        //判断用户是否可用：账号禁用
        if(userInfo.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //生成token
        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
        return token;
    }


    @Override
    public UserInfoVo info(String accessToken) {

        //获取用户id
        Integer userId =( Integer) JwtUtil.parseToken(accessToken).get("userId");
        //获取用户信息
        UserInfo userInfo = userInfoService.getById(userId);
        //封装用户信息
        UserInfoVo userInfoVo = new UserInfoVo( userInfo.getNickname(), userInfo.getAvatarUrl());

        return userInfoVo;
    }
}
